package cn.leizp.springboot.server.netmanger.telnet;

import cn.leizp.springboot.server.netmanger.common.inter.ResultData;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.time.Instant;
import java.util.HashMap;

public class MySwitch {
    private static HashMap<String, MySwitch> mySwitchMap = new HashMap<>();
    public static MySwitch getInstance(String mySwitchIp) {
        if(!mySwitchMap.containsKey(mySwitchIp)){
            mySwitchMap.put(mySwitchIp, new MySwitch(mySwitchIp));
        }
        MySwitch mySwitch = mySwitchMap.get(mySwitchIp);
        return mySwitch;
    }


    private String ipAddr;
    private long lastOptTime = 0L;
    private long TIMEOUT = 600L; // 10分钟

    public MySwitch(String ipAddr){
        this.ipAddr = ipAddr;
    }

    private boolean connected = false;
    private void connect() {
        try {
            if(!connected || Instant.now().getEpochSecond() - lastOptTime > TIMEOUT){
                // 未连接 或 连接但已超时
                socket = new Socket(ipAddr, 23);
                socket.setSoTimeout(2000);
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                writer = new PrintWriter(socket.getOutputStream(), true);
                waitForPrompt();
                writer.println("admin");
                waitForPrompt();
                writer.println("1qaz2wsx3edc");
                waitForPrompt();
            }
            //writer.println("");
            //String temp = waitForPrompt();
            //System.out.print(temp);

            connected = true;
            lastOptTime = Instant.now().getEpochSecond();
        }
        catch (Exception err){
            System.out.println(err.getMessage());
        }
    }

    public ResultData processCommand(String command){
        // 与交换机建立连接
        connect();

        writer.println(command);
        String temp = waitForPrompt();
        String resMessage = "";
        if(temp.endsWith("---- More ----")){
            int cnt = 0;
            do{
                cnt++;
                resMessage += temp.substring(0, temp.lastIndexOf("\r\n")+2);
                writer.println(" ");
                temp = waitForPrompt();
                if(temp.lastIndexOf("[42D") > 0)
                    temp = temp.substring(temp.lastIndexOf("[42D") + 4);
            }while(temp.endsWith("---- More ----"));
            cnt = (cnt + 1) / 2;
            while (cnt-- > 0){
                waitForPrompt();
            }
        }
        resMessage += temp;
        System.out.print(resMessage);
        return ResultData.ok(resMessage);
    }



    private Socket socket;
    private BufferedReader reader;
    private PrintWriter writer;
    boolean needRN = false;
    private boolean IsEnd(String str){
        if(str.endsWith("sername:") || str.endsWith("assword:"))
            return true;
        if(str.endsWith("cipher")){
            // 接下来除非遇到行结尾，否则结束符失效
            needRN = true;
        }
        if(needRN){
            if(str.endsWith("\r\n"))
                needRN = false;
            return false;
        }
        return str.endsWith(">") ||
                str.endsWith("]") ||
                str.endsWith("---- More ----");
    }

    private String waitForPrompt() {
        StringBuilder response = new StringBuilder();
        try {
            while (!IsEnd(response.toString())) {
                char ch = (char)reader.read();
                response.append(ch);
            }
        }
        catch (Exception err){
            System.err.println(err.getMessage());
        }
        finally {
            return response.toString();
        }

    }

    public void disconnect() throws IOException {
        if (writer != null) writer.close();
        if (reader != null) reader.close();
        if (socket != null) socket.close();
    }
}
